import ora from "ora";
import chalk from "chalk";
import updateVersion from "../core/updateVersion.js";
import updateChangelog from "../core/updateChangelog.js";
import build from "../core/build.js";
import appendChangelog from "../core/appendChangelog.js";
import revert from "../core/revert.js";
import { runCmdSync } from "../utils/runCmd.js";
import getPkgToolsConfig from "../utils/getPkgToolsConfig.js";
import { getNpmTag } from "../utils/npmTag.js";
import generatePackageJson from "../core/generatePackageJson.js";
import robot from "../core/robot.js";

/**
 * 发布组件
 * @param argv
 * @param options
 * @returns {Promise<void>}
 */
export default async (argv, options) => {
  if (!argv["skip-git-status"]) {
    console.log("git status --porcelain");
    const { stdout } = runCmdSync("git", ["status", "--porcelain"], {
      stdio: "pipe",
    });
    if (stdout) {
      console.log(chalk.red("Git工作目录不干净，请提交代码（commit）后再操作"));
      return;
    }
  }

  const { remoteInfo } = await updateVersion(options);

  // 更新 CHANGELOG.md
  await updateChangelog();

  // 跳过编译，发布源码
  if (!argv["skip-compile"]) {
    const result = await build(argv, options);
    if (result.failed) {
      // 发布失败，回退
      revert();
    }
    await generatePackageJson();
  }

  if (!argv["skip-append-changelog"]) {
    appendChangelog();
  }

  const publishSpinner = ora("开始发布...");
  publishSpinner.start();
  console.log(" ");

  const { outputPath, robotConfig = {} } = await getPkgToolsConfig();

  try {
    // --with-package-cli-service 主要为了发布时 让 process.argv 携带该值，分辨是否是使用 package-cli-service 发布的
    let args = ["publish"];
    // 然后没有跳过编译，则发布 outputPath 置顶的目录
    if (!argv["skip-compile"]) {
      args.push(outputPath);
    }
    const npmTag = getNpmTag();
    if (npmTag) {
      args = args.concat(["--tag", npmTag]);
    }
    args.push("--with-package-cli-service");
    // 跳过发布，测试用
    if (!argv["skip-publish"]) {
      console.log(`npm ${args.join(" ")}`);
      runCmdSync("npm", args, {
        stdio: [2, 2, 2],
      });
    }

    publishSpinner.succeed("发布成功！");
  } catch (err) {
    console.error(err);
    publishSpinner.fail("发布失败！");

    // 发布失败，回退
    revert();
    return;
  }

  // 提交本地 tags
  try {
    if (remoteInfo.stdout) {
      console.log("git push --tags");
      runCmdSync("git", ["push", "--tags"]);
    }
  } catch (err) {
    console.error(err);
  }

  if (!argv["skip-robot"] && robotConfig.robotUrl) {
    robot();
  }
};
